package class3;

import java.util.concurrent.TimeUnit;

/**
 * 使用单向链表模拟队列
 */
public class Code03_Queque {
    public static void main(String[] args) throws InterruptedException {

        MyQueue<Integer> myQueue = new MyQueue<>();
        TimeUnit.SECONDS.sleep(1L);
        myQueue.offer(1);
        myQueue.offer(2);
        myQueue.offer(3);

        System.out.println(myQueue.toString());
        Integer pop = myQueue.pop();
        System.out.println(pop);
        System.out.println(myQueue.toString());
        System.out.println(myQueue.peek());
        System.out.println(myQueue.toString());


    }

    static class Node<T> {
        T d;
        Node next;

        public Node(T d) {
            this.d = d;
        }
    }

    static class MyQueue<V> {
        private Node<V> head;
        private Node<V> tail;
        private int size;


        public String toString() {
            StringBuilder sb = new StringBuilder("[");
            Node temp = this.head;
            while (temp != null) {
                sb.append(temp.d).append(", ");
                temp = temp.next;
            }
            sb.delete(sb.lastIndexOf(", "), sb.lastIndexOf(" ") + 1);
            sb.append("]");
            return sb.toString();
        }

        public MyQueue() {
            head = null;
            tail = null;
            size = 0;
        }

        public int getSize() {
            return size;
        }

        public boolean isEmpty() {
            return size == 0;
        }

        // 进入队列
        public void offer(V value) {
            Node<V> cur = new Node<>(value);
            if(tail == null){
                head = tail = cur;
            }else{
                tail.next = cur; //尾节点下一个值为cur
                tail = cur; // 更新尾节点
            }
            size++;
        }

        // 弹出队列
        public V pop() {
            V ans = null;
            if (head != null) {
                ans = head.d;
                head = head.next;
                size--;
            }
            if (head == null) {
                tail = null;
            }
            return ans;
        }

        // 返回要弹出的值
        public V peek() {
            V ans = null;
            if (head != null) {
                ans = head.d;
            }
            return ans;
        }
    }
}

